package com.aweqy.librarymanager.controller;

import com.aweqy.librarymanager.entity.Borrower;
import com.aweqy.librarymanager.service.BorrowerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/borrower")
public class BorrowerController {
    @Autowired
    private BorrowerService borrowerService;

    @GetMapping("/list")
    public Page<Borrower> list(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "10") int size,
                               @RequestParam(required = false) String name) {
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            wrapper.like("name", name);
        }
        return borrowerService.page(new Page<>(page, size), wrapper);
    }

    @PostMapping("/add")
    public ResponseEntity<?> add(@RequestBody Borrower borrower) {
        if (!StringUtils.hasText(borrower.getName()) || !StringUtils.hasText(borrower.getIdCard()) || !StringUtils.hasText(borrower.getPhone())) {
            return ResponseEntity.badRequest().body("姓名、身份证号、电话不能为空");
        }
        if (borrowerService.lambdaQuery().eq(Borrower::getIdCard, borrower.getIdCard()).one() != null) {
            return ResponseEntity.badRequest().body("身份证号已存在，请勿重复添加");
        }
        try {
            boolean ok = borrowerService.save(borrower);
            if (!ok) {
                return ResponseEntity.status(500).body("保存失败，请联系管理员");
            }
            return ResponseEntity.ok(true);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("Duplicate entry") && e.getMessage().contains("id_card")) {
                return ResponseEntity.badRequest().body("身份证号已存在，请勿重复添加");
            }
            return ResponseEntity.status(500).body("保存失败，" + e.getMessage());
        }
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Borrower borrower) {
        return borrowerService.updateById(borrower);
    }

    @PostMapping("/delete")
    public boolean delete(@RequestParam Integer id) {
        return borrowerService.removeById(id);
    }
} 